﻿using DLL.FlushRobot.MS.Run;
using DLL.MSDM.Entity;
using DLL.Net.DB.Recorder.CRUD.Service;
using DLL.Net.MS.Models;
using DLL.Net.RJSpeech;
using DLL.NET.BindingInjector;
using DLL.NET.DJ.MSDM;
using DLL.NET.Login.Account.Entity.DTO;
using DLL.NET50.DB.MS.AdviceAndDrug;
using DLL.NET50.DB.MS.AdviceAndDrug.ORM.Service;
using DLL.NET50.DB.MS.PIVASAndDicDrug.ORM;
using DLL.NET50.DB.PIVAS.ORM.Service;

using DLL.NET50.SerialPort.MCU.LED;
using DLL.Net60.AdviceLabel.Entity;

using DLL.Net60.MotionCtrl.ControlBase;
using DLL.NET60.DB.MS.Entity.DTO;
using DLL.NET70.Infrastructure.EventAggregator;
using DLL.NET70.Infrastructure.Prism.MVVM;
using DLL.NetStandard.FlushRobot.MS.Entity.Param;
using DLL.Standard.Infrastructure.Entity;
using DLL.Standard.Infrastructure.Log;
using DLL.WCL.UserWindow;
using Google.Protobuf.WellKnownTypes;
using Library.NetStandard.SoftDog;
using Prism.Commands;
using Prism.Events;
using Prism.Ioc;
using Prism.Mvvm;
using Prism.Regions;
using Prism.Services.Dialogs;

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Security.Policy;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
using System.Windows;
using System.Windows.Threading;

namespace Module.AutoRun.ViewModels
{
    public class PUC_AutoRunViewModel : CMVVMBase, IRegionMemberLifetime
    {
        #region local variable

        private CMS_WorkPointParam _workPoint = new CMS_WorkPointParam();
        private CMS_WorkConfigParam _workConfig = new CMS_WorkConfigParam();
        private CMS_DeviceConfigParam _deviceConfig = new CMS_DeviceConfigParam();

        private CDogRegsiter dog = new CDogRegsiter();
        private CRegsiterCode regCode = new CRegsiterCode();
        private adi_accountDTO _logAccount;
        private DTO_adi_dic_drug sDrug;//当前配的药
        private string drugCode = "";
        private int softType = 0;

        //扫码处理函数
        private int _surplusMode = 0;//结余模式0:结余模式，1：不结余模式

        private List<string> _adviceBars = new List<string>();//扫描到的医嘱条码
        private bool _needFlushBack = false;//回打溶媒标志位
        private long ret = 0;
        private bool _mcuConnectOK = false;//单片机联机状态
        private bool _regcodeOK = false;//加密狗连接状态
        private bool _scanBarMode = false;//用来标记是扫码模式还是单机模式0:单机模式，1：扫码模式
        private int ValidStation = 6;//设备工位
        private string _canUsedStation = "0-0-0-0-0-0";
        private int[] _array_CanUsedStationt = new int[6] { 0, 0, 0, 0, 0, 0 };
        private int _injectorHadUsedCount = 0;//用来标记注射器使用次数
        private bool _injectorHadUsed = false;//注射器是否已经使用过
        private bool _haveBottleInDevice = false;//用来标记设备上有没有西林瓶
        private int[] _array_InjectorHadUsedCount = new int[6] { 0, 0, 0, 0, 0, 0 };
        private bool[] _array_InjectorHadUsed = new bool[6] { false, false, false, false, false, false };//统配模式使用，注射器已经更换标志位

        private DispatcherTimer _timer;
        private CNavigateTopParam _topParam = new CNavigateTopParam();
        private CMS_AdviceAndDrugs _advicesForFlush = new CMS_AdviceAndDrugs();//正在配药使用的医嘱

        private float[] _remainDrugDose = new float[MaxColPointCount];//用来记录西林瓶内剩余药品的剂量

        #endregion local variable

        #region property

        #region combobox

        private int _DeviceConnectMode = 0;//0:单机模式，1：本机联机模式2：计费模式

        public int DeviceConnectkMode
        {
            get { return _DeviceConnectMode; }
            set { SetProperty(ref _DeviceConnectMode, value); }
        }

        private bool _EnableConnectMode = true;

        public bool EnableConnectMode
        {
            get { return _EnableConnectMode; }
            set
            {
                SetProperty(ref _EnableConnectMode, value);
            }
        }

        private int _TPFlushMode = 1;//1:统配模式，0：混合配药模式

        public int TPFlushMode
        {
            get { return _TPFlushMode; }
            set { SetProperty(ref _TPFlushMode, value); }
        }

        //EnableTPMode
        private bool _EnableTPMode = true;

        public bool EnableTPMode
        {
            get { return _EnableTPMode; }
            set
            {
                SetProperty(ref _EnableTPMode, value);
            }
        }

        #endregion combobox

        #region text

        private string _runState = "";

        public string RunState
        {
            get { return _runState; }
            set
            {
                SetProperty(ref _runState, value);
            }
        }

        //StateColor
        private string _StateColor = "Red";

        public string StateColor
        {
            get { return _StateColor; }
            set
            {
                SetProperty(ref _StateColor, value);
            }
        }

        #endregion text

        #region Button

        //按钮属性变量
        private bool _btnResetIsEnabled = true;

        public bool BtnResetIsEnabled
        {
            get { return _btnResetIsEnabled; }
            set
            {
                SetProperty(ref _btnResetIsEnabled, value);
                // ResetCommand.RaiseCanExecuteChanged();
            }
        }

        //自动运行
        private bool _btnAutoRunIsEnabled = false;

        public bool BtnAutoRunIsEnabled
        {
            get { return _btnAutoRunIsEnabled; }
            set
            {
                SetProperty(ref _btnAutoRunIsEnabled, value);
                //RunFlushCommand.RaiseCanExecuteChanged();
            }
        }

        //换针
        private bool _btnReplaceIsEnabled = false;

        public bool BtnReplaceIsEnabled
        {
            get { return _btnReplaceIsEnabled; }
            set
            {
                SetProperty(ref _btnReplaceIsEnabled, value);
                //ReplaceCommand.RaiseCanExecuteChanged();
            }
        }

        //编辑药品
        private bool _btnDrugIsEnabled = false;

        public bool BtnDrugIsEnabled
        {
            get { return _btnDrugIsEnabled; }
            set
            {
                SetProperty(ref _btnDrugIsEnabled, value);
                //EidtDrugCommand.RaiseCanExecuteChanged();
            }
        }

        //清洗
        private bool _btnCleanIsEnabled = false;

        public bool BtnCleanIsEnabled
        {
            get { return _btnCleanIsEnabled; }
            set
            {
                SetProperty(ref _btnCleanIsEnabled, value);
                //BtnCleanCommand.RaiseCanExecuteChanged();
            }
        }

        //半开夹爪
        private bool _btnJzIsEnabled = false;

        public bool BtnJzIsEnabled
        {
            get { return _btnJzIsEnabled; }
            set
            {
                SetProperty(ref _btnJzIsEnabled, value);
                //BtnJzCommand.RaiseCanExecuteChanged();
            }
        }

        //清空
        private bool _btnClearIsEnabled = true;

        public bool BtnClearIsEnabled
        {
            get { return _btnClearIsEnabled; }
            set
            {
                SetProperty(ref _btnClearIsEnabled, value);
                //ClearBottleLabelCommand.RaiseCanExecuteChanged();
            }
        }

        //返回
        private bool _btnBackIsEnabled = true;

        public bool BtnBackIsEnabled
        {
            get { return _btnBackIsEnabled; }
            set
            {
                SetProperty(ref _btnBackIsEnabled, value);
                //GoBackCommand.RaiseCanExecuteChanged();
            }
        }

        //放药位
        private bool _btnPutDrugIsEnabled = false;

        public bool BtnPutDrugIsEnabled
        {
            get { return _btnPutDrugIsEnabled; }
            set
            {
                SetProperty(ref _btnPutDrugIsEnabled, value);
                //PutDrugCommand.RaiseCanExecuteChanged();
            }
        }

        #endregion Button

        #region 药品编辑

        //编辑药品
        private int _cbxSIndex_EditDrug = -1;

        public int cbxSIndex_EditDrug
        {
            get { return _cbxSIndex_EditDrug; }
            set { SetProperty(ref _cbxSIndex_EditDrug, value); }
        }

        private bool _cbxEnable_EditDrug = false;

        public bool CbxEnable_EditDrug
        {
            get { return _cbxEnable_EditDrug; }
            set
            {
                SetProperty(ref _cbxEnable_EditDrug, value);
            }
        }

        private List<DTO_adi_dic_drug> _scanedDrugs = new List<DTO_adi_dic_drug>() { };

        public List<DTO_adi_dic_drug> ScanedDrugs
        {
            get { return _scanedDrugs; }
            set { SetProperty(ref _scanedDrugs, value); }
        }

        private CMV_Drug _mvDrug = new CMV_Drug();

        public CMV_Drug mvDrug
        {
            get { return _mvDrug; }
            set
            {
                SetProperty(ref _mvDrug, value);
            }
        }

        private List<CMV_Drug> _mvDrugs = new List<CMV_Drug>();

        public List<CMV_Drug> MVDrugs
        {
            get { return _mvDrugs; }
            set { SetProperty(ref _mvDrugs, value); }
        }

        #endregion 药品编辑

        #endregion property

        private IContainerExtension _container;
        private IEventAggregator _eventAggregator;
        private IRegionManager _regionManager;
        private IAdviceAndDicDrugsService _AdviceAndDrugService;
        private IAdviceDrugService _adviceDrugService;
        private IAdviceExecuteService _adviceExecuteService;
        private IAdviceRecordService _RecorderService;
        private IDialogService _dialogService;
        private IPIVASAndDicDrug _pivasAndDicDrug;
        private IMotionCtrlBase _nMotionCtrl;
        private IMSDMSendCommandMessage _CMD;
        public IDJ_MS cDJ;
        public IControlLED cLED;
        private IMS_HP_AutoFlush _autoRun;

        public PUC_AutoRunViewModel(IRegionManager regionManager,

            IEventAggregator eventAggregator,
            IContainerExtension container,
            IAdviceAndDicDrugsService adviceAndDicDrugsService,
            IAdviceDrugService adviceDrugService,
            IAdviceExecuteService adviceExecuteService,
            IAdviceRecordService adviceRecorderService,
            IPIVASAndDicDrug pivasAndDicDrug,
            IControlLED controlLED,
            IDJ_MS dJ_MS,
            IMotionCtrlBase motionCtrlBase,
            IMSDMSendCommandMessage sendCommandMsg,
            IMS_HP_AutoFlush mS_HP_AutoFlush,
            IDialogService dialogService
        ) : base(regionManager, eventAggregator)
        {
            _regionManager = regionManager;
            _eventAggregator = eventAggregator;
            _container = container;
            _AdviceAndDrugService = adviceAndDicDrugsService;
            _adviceDrugService = adviceDrugService;
            _adviceExecuteService = adviceExecuteService;
            _RecorderService = adviceRecorderService;
            _dialogService = dialogService;
            _pivasAndDicDrug = pivasAndDicDrug;
            _nMotionCtrl = motionCtrlBase;
            cLED = controlLED;
            cDJ = dJ_MS;
            _CMD = sendCommandMsg;
            _autoRun = mS_HP_AutoFlush;
            _logAccount = (adi_accountDTO)container.Resolve(typeof(adi_accountDTO));
            _nMotionCtrl.ReadParam();
            if (_logAccount.MJobNumber == "renjie")
            {
                _logAccount.SCAN_USER_NUM = "admin";
            }
        }

        #region 获取可以使用的站台

        private int[] GetCanUsedStation()
        {
            int[] canUsed = new int[6] { 0, 0, 0, 0, 0, 0 };
            for (int i = 2; i < _nMotionCtrl.UsedAxisCount; i++)
            {
                int enabled = _nMotionCtrl.motionParam.axis.runParam.axisesRunParam[i].AxisEnable;
                canUsed[i - 2] = enabled;
            }
            return canUsed;
        }

        private string ArrayToStr(int[] arr)
        {
            string str = "";
            for (int i = 0; i < arr.Length; i++)
            {
                int enabled = arr[i];
                str += enabled.ToString();
                if (i < arr.Length - 1)
                {
                    str += "-";
                }
            }
            return str;
        }

        private string GetCanUsedStationStr()
        {
            int[] arr = GetCanUsedStation();
            _array_CanUsedStationt = arr;
            _topParam.CanUsedStation = arr;
            return ArrayToStr(arr);
        }

        #endregion 获取可以使用的站台

        #region navigate

        public bool KeepAlive
        {
            get
            {
                return false;//这个的作用是，只要离开当前切面，就注销掉当前页面
                //return true;//
            }
        }

        private void NavigateToTop()
        {
            string path = "PUC_MS_OnlineTop";
            if (DeviceConnectkMode == 0)
            {
                //单机模式
                path = "PUC_MS_StandAlone";
            }
            else
            {
                path = "PUC_MS_ScanBar";
            }

            NavigateToTop(path);
            if ((_nMotionCtrl.CardConnected == 1) && (_nMotionCtrl.HomeOK == 1))
            {
                EnableAllBtn();
            }
            else
            {
                ShowRunState("请先复位！", LogLevel.Warning);
            }
        }

        private void NavigateToTop(string navigatePath)
        {
            int topEnable = 0;
            if (navigatePath != null)
            {
                if ((_logAccount.MAuthority > 3) || ((_nMotionCtrl.CardConnected == 1) && (_nMotionCtrl.HomeOK == 1)))
                {
                    topEnable = 1;
                }
                else
                {
                    topEnable = 0;
                }
                _topParam.AllEnable = topEnable;
                var parameters = new NavigationParameters();
                parameters.Add("topParam", _topParam);
                _regionManager.RequestNavigate("MS_BarCodeContentRegion", navigatePath, parameters);
            }
        }

        private void SetValueToNavigateToTopParam()
        {
            _topParam.TPFlushMode = TPFlushMode;
            _topParam.StationColNum = ValidStation;
            _topParam.DeviceConnectkMode = DeviceConnectkMode;
        }

        public void NavigateToShowLable(string canUsedStation)
        {
            string navigatePath = "";
            if (ValidStation == 4)
            {
                navigatePath = "PUC_ShowAdviceLabel4";
            }
            else if (ValidStation == 6)
            {
                navigatePath = "PUC_ShowAdviceLabel6";
            }
            if (navigatePath != null)
            {
                NavigateToShowLable(canUsedStation, navigatePath);
            }
        }

        private void NavigateToShowLable(string canUsedStation, string navigatePath)
        {
            if (navigatePath != null)
            {
                //_regionManager.RequestNavigate("MS_BarCodeContentRegion", navigatePath, NavigationComplete);
                var parameters = new NavigationParameters();
                parameters.Add("canUsedStation", canUsedStation);
                if (canUsedStation != null)
                    _regionManager.RequestNavigate("MS_BottleLabelContentRegion", navigatePath, parameters);
            }
        }

        public override void ConfirmNavigationRequest(NavigationContext navigationContext, Action<bool> continuationCallback)
        {
            bool result = true;
            if (navigationContext.Uri.ToString() != "PUC_AutoRun")
            {
                RemoveView();
            }

            continuationCallback(result);
        }

        private void RemoveView()
        {
            IRegion region = _regionManager.Regions["MS_BottleLabelContentRegion"];
            region.RemoveAll();

            IRegion region3 = _regionManager.Regions["MS_BarCodeContentRegion"];
            region3.RemoveAll();
        }

        private void RemoveViewAndRegion()
        {
            IRegion region = RegionManager.Regions["MS_BarCodeContentRegion"];
            if (region != null)
            {
                foreach (var obj in region.Views)
                {
                    region.Remove(obj);
                }
            }
            region = RegionManager.Regions["MS_BottleLabelContentRegion"];
            if (region != null)
            {
                foreach (var obj in region.Views)
                {
                    region.Remove(obj);
                }
            }
            RegionManager.Regions.Remove("MS_BarCodeContentRegion");
            RegionManager.Regions.Remove("MS_BottleLabelContentRegion");
        }

        #endregion navigate

        #region Initialize

        private int AllowCount = 0;
        private int CurrentUsedCount = 0;

        public override void Loaded()
        {
            LogMessage("加载配药界面！");
            System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
            stopwatch.Start(); //  开始监视代码
            RegisterCommandMsgReceive();
            RegisterMessageReceived();
            _eventAggregator.GetEvent<CMS_AdvicesMsgEvent>().Subscribe(Advices_ReceiveMsg);//注册接收消息
            _autoRun.ReadParamFile();
            _canUsedStation = GetCanUsedStationStr();//获取可以使用的站台
            ReadParam();
            InitializeVariable();
            ConnectMotionCard();
            SetValueToNavigateToTopParam();
            NavigateToTop();
            NavigateToShowLable(_canUsedStation);
            //_autoRun = new CMS_HP_AutoFlush(_nMotionCtrl, cLED, cDJ, _dialogService, _eventAggregator);
            //打开舵机控制串口
            cDJ.DJCtrl.ReadRunPosParam();
            cDJ.ReadComParam();
            cDJ.OpenCom();
            cLED.ReadComParam();
            if (_deviceConfig.enableMcu == 1)
            {
                cLED.OpenCom();
                cLED.ReadDeviceID();
                MCU_Connect();
            }
            else
            {
                _mcuConnectOK = true;
            }
            bool re = true;

            bool re1 = Dog_Connect();
            if (_logAccount.MAuthority < 4)
            {
                if ((false == re) || (false == re1))
                {
                    DisableAllExceptReset();
                }
                else
                {
                    if ((_nMotionCtrl.CardConnected == 1) && (_nMotionCtrl.HomeOK == 1))
                    {
                        _CMD.CM_ResetOver(1);
                        EnableAllBtn();
                    }
                    else
                    {
                        ShowRunState("请先复位！", LogLevel.Warning);
                    }
                }
                _CMD.SetFocuse(0);
            }
            else
            {
                //最高权限，默认回零成功
                _CMD.CM_ResetOver(1);
                EnableAllBtn();
            }
            if (_workConfig.EnableAutoReset == 1)
            {
                if (_logAccount.MAuthority <= 1)
                {
                    BtnReset();
                }
            }
            if (_workConfig.EnableBindingInjector == 1)
            {
                re = WR_CInjectorCount.Read(ref AllowCount, ref CurrentUsedCount);
                if (false == re)
                {
                    AllowCount = 0;
                    CurrentUsedCount = 0;
                    LogMessage("系统文件损坏，无法配药！");
                }
                else
                {
                    string str = "总量=" + AllowCount.ToString() + ";使用量=" + CurrentUsedCount.ToString();
                    SendCommandMessage(GlobalCommand.BindingInjector, str);
                }
            }

            _timer = new DispatcherTimer();
            _timer.Interval = TimeSpan.FromMilliseconds(200);
            _timer.Tick += timer1_Tick;
            _timer.Start();

            double milliseconds = GetUsedTotalTime(stopwatch);
            LogMessage("PUC_AutoRunViewModel   load intialize time=" + milliseconds.ToString());
            base.Loaded();
        }

        public override void UnLoaded()
        {
            //RemoveViewAndRegion();
            UnRegisterCommandMsgReceive();
            UnRegisterMessageReceived();
            _eventAggregator.GetEvent<CMS_AdvicesMsgEvent>().Unsubscribe(Advices_ReceiveMsg);//注销消息接收相应函数
            if (_deviceConfig.enableMcu == 1)
            {
                #region renjie

                if (cancellationSource != null)
                {
                    cancellationSource?.Cancel();
                    cancellationSource?.Dispose();
                }
                ContinueRefreshLED = false;

                #endregion renjie
            }

            LogMessage("退出自动配药界面！");
            _timer.Stop();

            if (_deviceConfig.enableMcu == 1)
            {
                cLED.CloseAllLED();
                cLED.CloseCom();// CloseCom();
            }

            cDJ.CloseCom();
            base.UnLoaded();
        }

        private void SetRunningCurrent()
        {
            for (int i = 0; i < _nMotionCtrl.motionParam.motionCardParam.UsedAxisCount; i++)
            {
                //SetCurrent
                _nMotionCtrl.SetCurrent(i, (int)Current.Running, _nMotionCtrl.motionParam.axis.runParam.axisesRunParam[i].RunningCurrent);
            }
        }

        private void ConnectMotionCard()
        {
            try
            {
                //添加控制卡自动连接，要不然点击复位按钮无效
                if (_nMotionCtrl.CardConnected == 0)
                {
                    ret = _nMotionCtrl.Connect();
                    if (0 == ret)
                    {
                        ShowRunState("控制卡连接失败！点击界面上的复位按钮可以再次连接控制卡！", LogLevel.Warning);
                    }
                    else
                    {
                        SetRunningCurrent();
                    }
                }
                else
                {
                    SetRunningCurrent();
                }
            }
            catch (Exception e)
            {
                LogHelper.Warn("自动配药界面初始化出现异常" + e.Message);
            }
        }

        private void ReadParam()
        {
            CMS_WR_DeviceConfigParam wr_deviceConfig = new CMS_WR_DeviceConfigParam();
            CMS_WR_WorkConfigParam wr_workConfig = new CMS_WR_WorkConfigParam();
            CMS_WR_WorkPointParam wr_WorkPoint = new CMS_WR_WorkPointParam();
            wr_deviceConfig.ReadParam();
            wr_workConfig.ReadParam();
            wr_WorkPoint.ReadParam();

            _deviceConfig = wr_deviceConfig.Param;
            _workConfig = wr_workConfig.Param;
            _workPoint = wr_WorkPoint.Param;
        }

        private void InitializeVariable()
        {
            ValidStation = _deviceConfig.StationColNum;
            DeviceConnectkMode = _workConfig.WorkMode;
            if (0 == DeviceConnectkMode)
            {
                //单机模式，不可以切换统配和散配，不可以清空瓶贴
                EnableTPMode = false;//单机模式不支持混配模式
                TPFlushMode = 1;//默认统配模式
                BtnClearIsEnabled = false;//屏蔽清空瓶贴按钮
                _scanBarMode = false;//单机文件模式
            }
            else
            {
                //扫码模式
                BtnClearIsEnabled = true;
                _scanBarMode = true;
            }
            _injectorHadUsed = false;//注射器已经更换标志位
            InitializeInjetor();
        }

        private bool MCU_Connect()
        {
            if (_deviceConfig.enableMcu == 0)
            {
                _mcuConnectOK = true;
            }
            else
            {
                if (_logAccount.MJobNumber != "renjie")
                {
                    //读取单片机数据
                    bool re = cLED.IsConnect;
                    if (false == re)
                    {
                        _mcuConnectOK = false;
                        ShowRunState("单片机连接失败！无法进行配药！", LogLevel.Warning);
                        BtnBackIsEnabled = true;
                        return false;
                    }
                    else
                    {
                        string deviceID = "";
                        bool re1 = cLED.ReadDeviceID(ref deviceID);
                        if (false == re1)
                        {
                            _mcuConnectOK = false;
                            ShowRunState("单片机连接失败！无法进行配药！", LogLevel.Warning);
                            BtnBackIsEnabled = true;
                            return false;
                        }
                        else
                        {
                            if (deviceID != _deviceConfig.DeviceID)
                            {
                                _mcuConnectOK = false;
                                ShowRunState("设备编码不匹配！无法进行配药！", LogLevel.Warning);
                                BtnBackIsEnabled = true;
                                return false;
                            }
                            else
                            {
                                _mcuConnectOK = true;
                            }
                        }
                    }
                }
                else
                {
                    _mcuConnectOK = true;
                }
            }

            return true;
        }

        private bool Dog_Connect()
        {
            if (_logAccount.MJobNumber != "renjie")
            {
                bool ret = dog.GetHadRegInfo(ref regCode);
                if (false == ret)
                {
                    ShowRunState("注册码无效，无法读取加密狗数据！", LogLevel.Warning);
                    BtnBackIsEnabled = true;
                    return false;
                }
                if ((regCode.deviceCode == "198609268") && (regCode.trainFlag == 714) && (regCode.customerID == "12228") && (regCode.allowDrugCount == 1222))
                {
                    //是测试加密狗
                    softType = 2;
                    _regcodeOK = true;
                }
                else
                {
                    //判断设备序列号是否正确
                    string deviceID = _deviceConfig.DeviceID;
                    if (_mcuConnectOK == true)
                    {
                        if (regCode.deviceCode != deviceID)
                        {
                            ShowRunState("注册码无效，无法进行配药，设备编码不匹配！", LogLevel.Warning);
                            BtnBackIsEnabled = true;
                            return false;
                        }
                    }
                    if (regCode.trainFlag != 714)
                    {
                        if (regCode.trainFlag > 100)
                        {
                            ShowRunState("试用注册码无效，无法进行配药！", LogLevel.Warning);
                            BtnBackIsEnabled = true;
                            return false;
                        }
                        //试用版本
                        _regcodeOK = true;
                        softType = 0;
                    }
                    else
                    {
                        if (92622 == regCode.allowDrugCount)
                        {
                            _regcodeOK = true;
                            softType = 1;//永久使用版本
                        }
                        else
                        {
                            ShowRunState("永久注册码无效，无法进行配药！", LogLevel.Warning);

                            BtnBackIsEnabled = true;
                            return false;
                        }
                    }
                }
            }
            else
            {
                _regcodeOK = true;
                _logAccount.SCAN_USER_NUM = "10000";
                softType = 1;
            }
            return true;
        }

        #endregion Initialize

        #region event

        public override void MessageReceived(string message)
        {
            try
            {
                if (message.Contains("PUC_MS_Clean"))
                {
                    if (message == "PUC_MS_Clean-UnLoaded")
                    {
                        if (_autoRun != null)
                        {
                            _autoRun.cDJ.OpenCom();
                        }
                        _CMD.SetFocuse(1);
                    }
                }
                else if (message == "PUC_EditDrug-UnLoaded")
                {
                    _CMD.SetFocuse(1);
                }
                else if (message == "PUC_EditDrug-Saved-OK")
                {
                    //接收药品保存成功的消息，并刷新保存的药品
                    //int count = _advicesForFlush.adviceAndDrugs.Count;
                    //string drugCode = sDrug.DRUG_CODE;
                    //List<DTO_adi_dic_drug> LnewDrug = _AdviceAndDrugService.GetDrugByCode(drugCode);
                    //if (LnewDrug.Count == 1)
                    //{
                    //    for (int i = 0; i < count; i++)
                    //    {
                    //        _advicesForFlush.adviceAndDrugs[i].Drugs[0] = LnewDrug[0];
                    //    }
                    //}
                    //else
                    //{
                    //    LogMessage("药品刷新失败！");
                    //}
                }
                else if (message == "StopRefreshLed")
                {
                    ContinueRefreshLED = false;
                }
                else if (message == "CloseMainWindow")
                {
                    UnLoaded();
                }
                else if (message.Contains("RunState"))
                {
                    string[] msg = message.Split("-");
                    if (msg.Count() == 3)
                    {
                        ShowRunState(msg[1], (LogLevel)(Convert.ToInt32(msg[2])));
                    }
                }
            }
            catch (Exception e)
            {
                ShowRunState("扫码出现异常！" + e.Message, LogLevel.Warning);
            }
        }

        public static Dictionary<string, object> Dic = new Dictionary<string, object>();

        public override void CommandMessageReceived(CCommandMessage message)
        {
            if (message.CommandStr == GlobalCommand.ExitApp)
            {
                if (_autoRun.cDJ.IsConnect)
                {
                    Thread t = new Thread(() =>
                    {
                        SplashWindow sw = new SplashWindow();
                        sw.Text = "正在关闭舵机，请稍等...............";
                        sw.WindowStartupLocation = WindowStartupLocation.Manual;
                        double swidth = sw.Width;
                        double cwidth = SystemParameters.WorkArea.Width;//得到屏幕工作区域宽度
                        double left = (cwidth - swidth) / 2;
                        sw.Left = left;
                        sw.Top = 300;
                        Dic["SplashWindow"] = sw;//储存
                        sw.ShowDialog();//不能用Show
                    });
                    t.SetApartmentState(ApartmentState.STA);//设置单线程
                    t.Start();
                    _autoRun.cDJ.MoveAllToBasePos();
                    if (Dic.ContainsKey("SplashWindow"))
                    {
                        SplashWindow sw = Dic["SplashWindow"] as SplashWindow;
                        sw.Dispatcher.Invoke((Action)(() => sw.Close()));//在sw的线程上关闭SplashWindow
                        Dic.Remove("SplashWindow");
                    }
                }
                UnLoaded();
            }
            else if (MSDM_CmdStr.StopRefreshLed == message.CommandStr)
            {
                ContinueRefreshLED = false;
            }
            else if ("RegisterInjectorOk" == message.CommandStr)
            {
                try
                {
                    string msg = message.value;
                    string[] msg2 = msg.Split("-");
                    AllowCount = Convert.ToInt32(msg2[0]);
                    CurrentUsedCount = Convert.ToInt32(msg2[1]);
                }
                catch (Exception e)
                {
                    LogMessage("注射器绑定出现异常：" + e.Message, LogLevel.Warning);
                }
            }
            base.CommandMessageReceived(message);
        }

        //接收单机模式，或扫码模式发送过来的医嘱信息
        private int _reAdviceIsValid = 0;

        private int _DJCloseIndex = 0;

        private void Advices_ReceiveMsg(CMS_AdvicesMsg advicesMsg)
        {
            if (advicesMsg.CommandStr == MSDM_CmdStr.AdviceOK)
            {
                _advicesForFlush = new CMS_AdviceAndDrugs();
                _advicesForFlush = (CMS_AdviceAndDrugs)advicesMsg.adviceAndDrugs.Clone();
                int firstUsedColID = GetFirtUsedColID();
                if (_advicesForFlush.adviceAndDrugs.Count > firstUsedColID)
                {
                    //扫码模式
                    ScanedDrugs = GetAllDrugs();
                    MVDrugs = GetDrugNames(_scanedDrugs);
                    _surplusMode = _advicesForFlush.adviceAndDrugs[firstUsedColID].SurPlusMode;
                    //这个地方添加点亮指示灯，如果设备正在配药，则不点亮指示灯，否则点亮指示灯
                    if (0 == _IsRunning)
                    {
                        GetShowLed(_advicesForFlush, ref SubLED);
                        TaskStartRefreshLED();

                        //打开夹爪
                        int closeIndex = _advicesForFlush.GetDJClosePosIndex();
                        if (closeIndex != _DJCloseIndex)
                        {
                            _DJCloseIndex = closeIndex;
                            TaskResetBottleJaw();
                        }
                    }
                    _reAdviceIsValid = 1;//医嘱是有效医嘱
                }
                else
                {
                    _reAdviceIsValid = 0;//医嘱是无效医嘱
                }
            }
        }

        private void TaskResetBottleJaw()
        {
            Task resetJaw = Task.Run(() =>
                {
                    _autoRun.cDJ.ResetBottleJaw(_DJCloseIndex);
                });
        }

        private void EnableNavigateLeftBtn(bool enable)
        {
            if (true == enable)
            {
                SendCommandMessage(GlobalCommand.EnableNavigateBtn, "1");
            }
            else
            {
                SendCommandMessage(GlobalCommand.EnableNavigateBtn, "0");
            }
        }

        private int GetFirtUsedColID()
        {
            for (int i = 0; i < _array_CanUsedStationt.Length; i++)
            {
                if (_array_CanUsedStationt[i] == 1)
                {
                    return i;
                }
            }
            return 0;
        }

        private List<DTO_adi_dic_drug> GetAllDrugs()
        {
            List<DTO_adi_dic_drug> _newScanedDrugs = new List<DTO_adi_dic_drug>(_scanedDrugs);
            if (_advicesForFlush != null)
            {
                if (_advicesForFlush.adviceAndDrugs.Count > 0)
                {
                    int adviceCount = _advicesForFlush.adviceAndDrugs.Count;
                    _newScanedDrugs.Clear();
                    for (int adviceIndex = 0; adviceIndex < adviceCount; adviceIndex++)
                    {
                        List<DTO_adi_dic_drug> drugs = _advicesForFlush.adviceAndDrugs[adviceIndex].Drugs;
                        int drugsCount = drugs.Count;
                        for (int drugIndex = 0; drugIndex < drugsCount; drugIndex++)
                        {
                            string drugCode = drugs[drugIndex].DRUG_CODE;
                            List<DTO_adi_dic_drug> localDrugs = _newScanedDrugs.Where(c => c.DRUG_CODE.Equals(drugCode)).ToList();
                            if (localDrugs.Count > 0)
                            {
                                //本地存在该药品，不用添加
                            }
                            else
                            {
                                _newScanedDrugs.Add(drugs[drugIndex]);
                            }
                        }
                    }
                }
            }
            return _newScanedDrugs;
        }

        private List<CMV_Drug> GetDrugNames(List<DTO_adi_dic_drug> drugs)
        {
            int count = drugs.Count;
            List<CMV_Drug> drugCodes = new List<CMV_Drug>();
            for (int drugIndex = 0; drugIndex < count; drugIndex++)
            {
                CMV_Drug mvdrug = new CMV_Drug();
                mvdrug.DrugName = drugs[drugIndex].DRUG_NAME;
                mvdrug.DrugCode = drugs[drugIndex].DRUG_CODE;
                drugCodes.Add(mvdrug);
            }
            return drugCodes;
        }

        //接收医嘱信息

        #endregion event

        #region 刷新LED指示灯

        protected const int MaxRowPointCount = 8;
        protected const int MaxSubRowPointCount = 5;
        protected const int MaxColPointCount = 8;
        private byte[,] SubLED = new byte[MaxRowPointCount, MaxColPointCount];
        public bool ContinueRefreshLED = false;

        private bool UpdateLED()
        {
            if (_deviceConfig.enableMcu == 1)
            {
                return OpenLedForFirstLoop(_advicesForFlush);
            }
            return true;
        }

        private void GetShowLed(CMS_AdviceAndDrugs adviceAndDrug, ref byte[,] SubLED)
        {
            List<CMS_AdviceAndDrug> allAdvices = adviceAndDrug.adviceAndDrugs;
            //初始化所有值为1
            for (int i = 0; i < MaxRowPointCount; i++)
            {
                for (int j = 0; j < MaxColPointCount; j++)
                {
                    SubLED[i, j] = 1;
                }
            }
            for (int col = 0; col < allAdvices.Count; col++)//医嘱执行单的总个数
            {
                //获取一个医嘱用药的数量
                CMS_AdviceAndDrug ae = allAdvices[col];
                if (ae.Enable == 1)
                {
                    //是有效的医嘱
                    int count = 0;
                    if (ae.Drugs[0].SOLVENT_FLAG == 2)
                    {
                        count = (int)ae.GetDrugCount() * 2;
                    }
                    else
                    {
                        count = (int)ae.GetDrugCount();
                    }
                    //循环每一行，赋值给当前列
                    for (int row = 0; row < 4; row++)
                    {
                        //初始化的时候，数组内的数据全为1；
                        if (row < count)
                        {
                            SubLED[row, col] = 0;
                        }
                        else
                        {
                            SubLED[row, col] = 1;
                        }
                    }
                }
            }
        }

        private bool OpenLedForFirstLoop(CMS_AdviceAndDrugs adviceAndDrug)
        {
            try
            {
                if (_deviceConfig.enableMcu == 1)
                {
                    if (adviceAndDrug.adviceAndDrugs.Count > 0)
                    {
                        return cLED.OpenLED(SubLED);
                    }
                }
                else
                {
                    return true;
                }
            }
            catch (Exception e)
            {
            }
            return true;
        }

        //配药结束，刷新显示LED灯
        private void UpdateLEDAfterFlushOver()
        {
            //if (_IsRunning == 0)
            {
                #region 根据医嘱信息，刷新显示LED灯

                int count = _advicesForFlush.adviceAndDrugs.Count;
                if (count > 0)
                {
                    GetShowLed(_advicesForFlush, ref SubLED);
                    TaskStartRefreshLED();
                }
                else
                {
                    ContinueRefreshLED = false;
                    cLED.CloseAllLED();
                }

                #endregion 根据医嘱信息，刷新显示LED灯
            }
        }

        #endregion 刷新LED指示灯

        #region TASK 刷新显示LED指示灯

        private Task LEDTask;
        private CancellationTokenSource cancellationSource;

        private void TaskStartRefreshLED()
        {
            // 常规使用
            if (_deviceConfig.enableMcu == 1)
            {
                if (false == ContinueRefreshLED)
                {
                    ContinueRefreshLED = true;

                    LEDTask = Task.Run(TaskRefreshLED);//, token
                }
            }
        }

        private void TaskRefreshLED()
        {
            while (ContinueRefreshLED)
            {
                if (cLED.IsConnect == false)
                {
                    ContinueRefreshLED = false;
                    return;
                }
                if (_advicesForFlush.adviceAndDrugs.Count == 0)
                {
                    //医嘱为空，则关闭所有LED
                    if (_workConfig.runningCloseLED == 0)
                    {
                        ContinueRefreshLED = false;
                        cLED.CloseAllLED();
                        return;
                    }
                }
                if (false == ContinueRefreshLED)
                {
                    cLED.CloseAllLED();
                    return;
                }
                bool ret = UpdateLED();
                if (false == ret)
                {
                    ContinueRefreshLED = false;
                    return;
                }
                for (int i = 0; i < 50; i++)
                {
                    Thread.Sleep(10);
                    if (false == ContinueRefreshLED)
                    {
                        cLED.CloseAllLED();
                        return;
                    }
                }
            }
        }

        #endregion TASK 刷新显示LED指示灯

        #region 定时器

        private void timer1_Tick(object sender, EventArgs e)
        {
            if ((_mcuConnectOK == false) || (_regcodeOK == false))
            {
                return;
            }
            //外部按钮处理
            IOProcess();
            //运行结束后，刷新显示下指示灯
        }

        private bool IO_Emg = false;
        private bool RunOkFlag = false;
        private int IO_StartRun = 0;
        private int IO_Reset = 0;

        //IO处理函数
        private void IOProcess()
        {
            //return;
            try
            {
                //if (ThreadOver == false)
                //{
                //    //说明线程正在运行，无法处理IO信号
                //    return;
                //}
                _timer.Stop();
                if ((_nMotionCtrl != null) && (_nMotionCtrl.CardConnected == 1))
                {
                    //控制卡连接
                    _nMotionCtrl.ReadInput();
                    ObservableCollection<int> AllInput = _nMotionCtrl.AllInput;
                    if (_nMotionCtrl.motionParam.motionCardParam.EmgIsClose == 1)
                    {
                        //急停按钮是常闭：emg=1;急停被按下 emg=0;急停
                        IO_Emg = Convert.ToBoolean(AllInput[_nMotionCtrl.motionParam.nIOSet.iEmgPort]);//
                    }
                    else
                    {
                        //急停按钮是常开
                        IO_Emg = !Convert.ToBoolean(AllInput[_nMotionCtrl.motionParam.nIOSet.iEmgPort]);//取反，信号总是取高电平有效，
                    }
                    if (false == IO_Emg)
                    {
                        //急停按钮被按下，不能进行复位或配药
                        ContinueRefreshLED = false;
                        ShowRunState("急停按钮被按下！无法配药或复位！", LogLevel.Warning);
                    }
                    else
                    {
                        if (_autoRun.IsFinished == true)
                        {
                            //设备没有在配药
                            if (_nMotionCtrl.HomeOK == 1)
                            {
                                IO_StartRun = AllInput[_nMotionCtrl.motionParam.nIOSet.iStartPort];
                                if (1 == IO_StartRun)
                                {
                                    if (false == AutoRunBtnIsDown)
                                    {
                                        RunFlush();
                                    }
                                }
                                //监测开始配药按钮
                            }
                            //监测复位按钮状态
                            IO_Reset = AllInput[_nMotionCtrl.motionParam.nIOSet.iResetPort];
                            if (1 == IO_Reset)
                            {
                                //开始复位动作
                                if (false == ResetBtnIsDown)
                                {
                                    BtnReset();
                                }
                            }
                        }
                    }
                }
                else
                {
                    ShowRunState("控制卡连接断开，复位重新连接控制卡", LogLevel.Warning);
                }
            }
            catch (Exception ex)
            {
                ShowRunState("定时器执行出现异常：" + ex.Message, LogLevel.Warning);
            }
            finally
            {
                _timer.Start();
            }
        }

        private bool ResetBtnIsDown = false;//复位按钮按下标志位
        private bool PutDrugBtnIsDown = false;//复位按钮按下标志位
        private bool ReplaceBtnIsDown = false;//复位按钮按下标志位
        private bool AutoRunBtnIsDown = false;

        private void RefreshLabelAfterReplaceInjector()
        {
            if (TPFlushMode == 1)
            {
                //统配模式
                if (_injectorHadUsedCount < _deviceConfig.InjectorAllowUsedCount)
                {
                    //注射器没有达到使用寿命，这时点换针是为了更改药品，配其他的药 删除瓶贴
                    LogMessage("统配模式：注射器没有达到使用寿命，进行换针");
                    //关闭LED
                    ContinueRefreshLED = false;
                    cLED.CloseAllLED();
                    _CMD.CM_ReplaceInjectorOver(0);
                    EnableConnectMode = true;
                    if (DeviceConnectkMode > 0)
                    {
                        //扫码模式，换针后，统配和混配可以进行切换
                        EnableTPMode = true;
                    }
                    _CMD.ClearBottleLabel();
                }
                else
                {
                    //注射器达到了使用寿命，但有可能药还没有配玩，所以不用删除瓶贴，不用恢复被屏蔽的状态
                    _CMD.CM_ReplaceInjectorOver(1);
                }
                _injectorHadUsedCount = 0;
                _injectorHadUsed = false;
                _autoRun.mInjectors.ResetInjector();
                _autoRun.ResetRemainDrugDose();
            }
            else
            {
                //混配模式的换针
                _injectorHadUsedCount = 0;
                _injectorHadUsed = false;
                _autoRun.mInjectors.ResetInjector();
                InitializeInjetor();

                _CMD.ClearBottleLabel();
                cLED.CloseAllLED();
                _CMD.CM_ReplaceInjectorOver(0);
                ContinueRefreshLED = false;
            }
        }

        //配药结束，判断是否需要换针
        private void JudgeReplaceInjectorAfterRunOver()
        {
            _autoRun.NeedleInBottle = false;
            if (1 == TPFlushMode)
            {
                //统配模式，判断注射器是否达到使用寿命

                if (_injectorHadUsedCount >= _deviceConfig.InjectorAllowUsedCount)
                {
                    //屏蔽所有按钮，除了换针
                    DisableAllBtnExceptReplace();
                    if (DeviceConnectkMode == 0)
                    {
                        //单机模式，屏蔽所有单机文件操作
                        _CMD.DisableAll();
                    }
                    ShowRunState("注射器达到使用寿命！请更换注射器！");
                }
            }
            else
            {
                //混配模式，获取达到使用寿命的注射器
                if (true == HaveInjectorAxceedWorkingLife())
                {
                    //有注射器达到使用寿命
                    string str = GetCanNotUsedInjector();//获取达到使用寿命的注射器
                    ShowRunState(str);
                    DisableAllBtnExceptReplace();
                }
            }
        }

        //判断是否达到注射器使用次数限制
        private int InjectorReachedUsageCountLimit()
        {
            if (1 == TPFlushMode)
            {
                //统配模式，判断注射器是否达到使用寿命

                if (_injectorHadUsedCount >= _deviceConfig.InjectorAllowUsedCount)
                {
                    //注射器达到使用寿命
                    return 1;
                }
                else
                {
                    return 0;
                }
            }
            else
            {
                //混配模式，获取达到使用寿命的注射器
                if (true == HaveInjectorAxceedWorkingLife())
                {
                    //有注射器达到使用寿命
                    return 1;
                }
                else
                {
                    return 0;
                }
            }
        }

        private void DisableAllBtn()
        {
            DisableFlushBtn();
            EnableNavigateLeftBtn(false);
        }

        private void DisableFlushBtn()
        {
            BtnResetIsEnabled = false;
            BtnBackIsEnabled = false;
            BtnAutoRunIsEnabled = false;
            BtnJzIsEnabled = false;
            BtnReplaceIsEnabled = false;
            BtnPutDrugIsEnabled = false;
            BtnDrugIsEnabled = false;
            BtnCleanIsEnabled = false;
        }

        private void DisableAllExceptReset()
        {
            BtnResetIsEnabled = true;
            BtnBackIsEnabled = false;
            BtnAutoRunIsEnabled = false;
            BtnJzIsEnabled = false;
            BtnReplaceIsEnabled = false;
            BtnPutDrugIsEnabled = false;
            BtnDrugIsEnabled = false;
            BtnCleanIsEnabled = false;
            EnableTPMode = false;
            EnableConnectMode = false;
        }

        private void DisableAllBtnExceptReplace()
        {
            BtnResetIsEnabled = false;
            BtnBackIsEnabled = false;
            BtnAutoRunIsEnabled = false;
            BtnJzIsEnabled = false;
            BtnReplaceIsEnabled = true;
            BtnPutDrugIsEnabled = false;
            BtnDrugIsEnabled = false;
            BtnCleanIsEnabled = false;
            EnableNavigateLeftBtn(false);
        }

        private void EnableAllBtn()
        {
            BtnResetIsEnabled = true;
            BtnBackIsEnabled = true;
            BtnAutoRunIsEnabled = true;
            BtnJzIsEnabled = true;
            EnableConnectMode = true;
            BtnCleanIsEnabled = true;

            BtnReplaceIsEnabled = true;

            if (_logAccount.MAuthority > 1)
            {
                BtnDrugIsEnabled = true;
            }
            BtnPutDrugIsEnabled = true;
            EnableNavigateLeftBtn(true);
        }

        #endregion 定时器

        #region 界面按钮指令

        #region 复位

        //resetCommand
        public DelegateCommand ResetCommand
        {
            get { return new DelegateCommand(BtnReset).ObservesCanExecute(() => BtnResetIsEnabled); }
        }

        //复位
        private void BtnReset()
        {
            bool bre = false;
            if (true == ContinueRefreshLED)
            {
                ContinueRefreshLED = false;
                LEDTask.Wait();
            }

            cDJ.OpenCom();
            if (_deviceConfig.enableMcu == 1)
            {
                cLED.ReadDeviceID();
                cLED.OpenCom();
                bre = MCU_Connect();
                if (false == bre)
                {
                    DisableAllExceptReset();
                    _CMD.CM_ResetOver(0);
                    return;
                }
            }
            else
            {
                _mcuConnectOK = true;
            }
            bre = Dog_Connect();
            if (false == bre)
            {
                DisableAllExceptReset();
                _CMD.CM_ResetOver(0);
                return;
            }
            //开启复位线程
            ResetBtnIsDown = true;
            ShowRunState("开始进行复位动作.....！", LogLevel.Information);

            if (_deviceConfig.enableMcu == 1)
            {
                cLED.CloseAllLED();
            }
            _CMD.CM_ResetStart(0);//发送开始复位消息
            DisableAllBtn();
            EnableConnectMode = false;
            _injectorHadUsed = false;
            InitializeInjetor();

            _autoRun.ResetRemainDrugDose();
            _remainDrugDose = _autoRun.RemainDrugDose;
            _autoRun.mInjectors.ResetInjector();
            _advicesForFlush.adviceAndDrugs.Clear();
            _nMotionCtrl.WorkPointID = 0;

            TaskFactory factory = Task.Factory;
            Task<int> task = factory.StartNew<int>(TaskReset);
            task.ContinueWith(TaskResetOver);
        }

        private int TaskReset()
        {
            bool re = ReConnect();
            if (false == re)
            {
                return 0;
            }
            _timer.Start();
            return 1;
        }

        private void TaskResetOver(Task<int> t)
        {
            int resetResult = t.Result;
            BtnResetOver(resetResult);
        }

        private void BtnResetOver(int resetResult)
        {
            LogMessage("复位完成！");
            ResetBtnIsDown = false;
            EnableConnectMode = true;
            BtnResetIsEnabled = true;//复位失败，只有复位按钮可以使用
            if (1 == resetResult)
            {
                SpeakAsync("复位已完成，请换针！");
                ShowRunState("复位成功！", LogLevel.Information);
                RunOkFlag = true;
                _nMotionCtrl.ExitType = 0;
                EnableAllBtn();
                _CMD.CM_ResetOver(1);
            }
            else
            {
                ShowRunState("复位失败！", LogLevel.Information);
                RunOkFlag = false;
                _nMotionCtrl.ExitType = 0;
                _CMD.CM_ResetOver(0);
                //复位失败
            }
            _nMotionCtrl.WriteChannelOut(_nMotionCtrl.motionParam.nIOSet.oResetLed, 0);
            _autoRun.NeedleInBottle = false;
            _remainDrugDose = _autoRun.RemainDrugDose;
            _advicesForFlush.adviceAndDrugs.Clear();
            cLED.CloseAllLED();
            _CMD.ClearBottleLabel();
        }

        private bool ReConnect()
        {
            //连接控制卡
            try
            {
                if (0 == _nMotionCtrl.CardConnected)
                {
                    ret = _nMotionCtrl.Connect();
                    if (0 == ret)
                    {
                        ShowRunState("连接控制卡失败", LogLevel.Warning);
                        return false;
                    }
                    else
                    {
                        ShowRunState("连接控制卡成功！", LogLevel.Information);
                    }
                }

                //回零
                if (1 == _nMotionCtrl.CardConnected)
                {
                    _nMotionCtrl.WriteChannelOut(_nMotionCtrl.motionParam.nIOSet.oResetLed, 1);
                    _nMotionCtrl.AllAxisHome();
                    if (0 == _nMotionCtrl.HomeOK)
                    {
                        ShowRunState("回零失败！", LogLevel.Warning);
                        return false;
                    }

                    //设置加工电流
                    ret = SetWorkCurrent();
                    if (0 == ret)
                    {
                        ShowRunState("设置电机运行电流失败", LogLevel.Warning);
                        return false;
                    }
                    else
                    {
                        ShowRunState("设置电机加工运行电流完成", LogLevel.Information);
                    }
                }
            }
            catch (Exception ex)
            {
                LogMessage("复位异常：" + ex.Message);
                return false;
            }

            return true;
        }

        private int SetWorkCurrent()
        {
            for (int i = 0; i < _nMotionCtrl.motionParam.motionCardParam.UsedAxisCount; i++)
            {
                ret = _nMotionCtrl.SetCurrent(i, (int)Current.Running, _nMotionCtrl.motionParam.axis.runParam.axisesRunParam[i].RunningCurrent);
                if (0 == ret)
                {
                    return 0;
                }
            }
            return 1;
        }

        #endregion 复位

        #region 配药

        private DateTime putStart = DateTime.Now;
        private DateTime putEnd = DateTime.Now;
        private int _IsRunning = 0;

        //配药
        public DelegateCommand RunFlushCommand
        {
            get { return new DelegateCommand(RunFlush).ObservesCanExecute(() => BtnAutoRunIsEnabled); }
        }

        private void RunFlush()
        {
            try
            {
                //刷新显示加工信息
                _CMD.CM_ClearLogMsg();
                LogMessage("点击了配药按钮！");
                _autoRun.advices = new CMS_AdviceAndDrugs();
                ret = CanRun();
                if (0 == ret)
                { return; }
                ShowRunState("开始配药！", LogLevel.Information);
                BroadcastDrugName();//播报药品名称
                AutoRunBtnIsDown = true;
                EnableConnectMode = false;
                EnableTPMode = false;
                _haveBottleInDevice = true;
                _autoRun.IsFinished = false;
                _IsRunning = 1;
                _injectorHadUsed = true;
                _injectorHadUsedCount++;
                for (int i = 0; i < _advicesForFlush.adviceAndDrugs.Count; i++)
                {
                    _array_InjectorHadUsed[i] = true;
                    _array_InjectorHadUsedCount[i] = _array_InjectorHadUsedCount[i] + 1;
                }

                _nMotionCtrl.WriteChannelOut(_nMotionCtrl.motionParam.nIOSet.oStartLed, 1);
                SaveAdviceToRecorder_Start();//开始配药的时候，保存医嘱到数据库
                _CMD.CM_RunStart(0);

                _autoRun.advices = (CMS_AdviceAndDrugs)_advicesForFlush.Clone();
                ShowRunState("进入自动配药线程", LogLevel.Information);
                if (DeviceConnectkMode != 0)
                {
                    //不是单机模式，保存日志
                    _autoRun.jobNumber = _logAccount.MJobNumber;
                    _autoRun.WorkMode = DeviceConnectkMode;
                    _advicesForFlush = new CMS_AdviceAndDrugs();//清空接收到的医嘱
                }
                _nMotionCtrl.IsAutoRun = 1;
                if (_deviceConfig.TestMode == 0)
                {
                    TaskFactory factory = Task.Factory;
                    Task<int> task = factory.StartNew<int>(TaskAutoRun);
                    task.ContinueWith(TaskAutoRunOver);
                }
                else
                {
                    //测试模式
                    TaskFactory factory = Task.Factory;
                    Task<int> task = factory.StartNew<int>(Task_TestMode);
                    task.ContinueWith(TaskAutoRunOver);
                }

                DisableAllBtn();//屏蔽所有按钮
                if (DeviceConnectkMode > 0)
                {
                    //扫码模式，清空瓶贴
                    _CMD.ClearBottleLabel();//清空瓶贴
                    _reAdviceIsValid = 0;
                }
                if (_deviceConfig.enableMcu == 1)
                {
                    if (_workConfig.runningCloseLED == 0)
                    {
                        cLED.CloseAllLED();
                        ContinueRefreshLED = false;
                    }
                }
                _CMD.SetFocuse(1);
            }
            catch (Exception ex)
            {
                LogMessage("RunFlush出现异常：" + ex.Message);
            }
        }

        private void SaveAdviceToRecorder_Start()
        {
            try
            {
                if ((DeviceConnectkMode > 0))
                {
                    _adviceBars = _advicesForFlush.GetScanBar();
                    _RecorderService.AddStartFlush(_adviceBars);
                }
            }
            catch (Exception e)
            {
                LogMessage("保存医嘱到本地数据库出现异常：" + e.Message);
            }
        }

        private List<string> GetDrugName()
        {
            List<string> list = new List<string>();
            for (int i = 0; i < _advicesForFlush.adviceAndDrugs.Count; i++)
            {
                if (_advicesForFlush.adviceAndDrugs[i] != null)
                {
                    if (_advicesForFlush.adviceAndDrugs[i].Enable == 1)
                    {
                        if (_advicesForFlush.adviceAndDrugs[i].Drugs != null)
                        {
                            if (_advicesForFlush.adviceAndDrugs[i].Drugs.Count > 0)
                            {
                                string drugName = _advicesForFlush.adviceAndDrugs[i].Drugs[0].DRUG_NAME;
                                list.Add(drugName);
                            }
                        }
                    }
                }
            }
            return list;
        }

        private int CanRun()
        {
            if (_workConfig.EnableBindingInjector == 1)
            {
                if (CurrentUsedCount >= AllowCount)
                {
                    LogMessage("允许使用的注射器数量结束，无法配药", LogLevel.Warning);
                    return 0;
                }
            }

            if (_advicesForFlush.adviceAndDrugs.Count == 0)
            {
                ShowRunState("医嘱数量为0，无法进行配药", LogLevel.Warning);
                return 0;
            }
            if (_nMotionCtrl.HomeOK == 0)
            {
                ShowRunState("没有回零，无法进行配药！", LogLevel.Warning);
                return 0;
            }
            if (_mcuConnectOK == false)
            {
                ShowRunState("单片机没有连接，无法配药", LogLevel.Warning);
                return 0;
            }
            if (_nMotionCtrl.CardConnected == 0)
            {
                ShowRunState("控制卡没有连接，无法配药", LogLevel.Warning);
                return 0;
            }
            if ((false == _injectorHadUsed) && (1 == _workConfig.EnableBindingInjector))
            {
                int count = GetUsedAdviceCount();
                DialogParameters dp = new DialogParameters();
                dp.Add("Value", count);
                _dialogService.ShowDialog("PUC_GetInjectorBar", dp, OnDialogClosed, "CustomDialogWindow");
                if (false == bindOK)
                {
                    LogMessage("注射器绑定失败，无法配药！", LogLevel.Warning);
                    return 0;
                }
                else
                {
                    CurrentUsedCount += count;
                    string str = "总量=" + AllowCount.ToString() + ";使用量=" + CurrentUsedCount.ToString();
                    SendCommandMessage(GlobalCommand.BindingInjector, str);
                    WR_CInjectorCount.Save(AllowCount, CurrentUsedCount);
                }
            }
            if (1 == _surplusMode)
            {
                //结余模式
                bool re = Surplus_BottleVolumeIsEnough();
                if (false == re)
                {
                    return 0;
                }
            }
            bool emg = false;
            int ret = _nMotionCtrl.GetEmgState(ref emg);
            if (0 == ret)
            {
                return 0;
            }
            if ((false == emg))
            {
                ShowRunState("急停按钮被按下，无法配药", LogLevel.Warning);
                return 0;
            }
            if (TPFlushMode == 1)
            {
                //统配模式
                if (_deviceConfig.InjectorAllowUsedCount < _injectorHadUsedCount)
                {
                    ShowRunState("注射器达到使用次数，无法配药，请换针！", LogLevel.Warning);
                    return 0;
                }
            }
            else
            {
                bool bret = HaveInjectorAxceedWorkingLife();
                if (true == bret)
                {
                    ShowRunState("有的注射器达到使用次数，无法配药，请换针！", LogLevel.Warning);
                    return 0;
                }
            }
            if (_autoRun.IsFinished == false)
            {
                ShowRunState("配药还没有结束，无法配药", LogLevel.Warning);
                return 0;
            }
            if (false == BtnAutoRunIsEnabled)
            {
                return 0;
            }
            if (false == _regcodeOK)
            {
                ShowRunState("注册码无效，无法配药", LogLevel.Warning);
                return 0;
            }
            if (_logAccount.MAuthority < 4)
            {
                if (false == dog.IsLogIn())
                {
                    ShowRunState("加密狗丢失，无法配药", LogLevel.Warning);

                    return 0;
                }
            }
            return 1;
        }

        private int GetUsedAdviceCount()
        {
            int count = 0;
            for (int i = 0; i < _advicesForFlush.adviceAndDrugs.Count; i++)
            {
                if (_advicesForFlush.adviceAndDrugs[i].AdviceHadStop == 0)
                {
                    count++;
                }
            }
            return count;
        }

        private bool bindOK = false;

        private void OnDialogClosed(IDialogResult result)
        {
            var bresult = result as DialogResult;
            if (bresult.Result == ButtonResult.Yes)
            {
                bindOK = true;
            }
            else
            {
                bindOK = false;
            }
        }

        private bool Surplus_BottleVolumeIsEnough()
        {
            int adviceCount = _advicesForFlush.adviceAndDrugs.Count;
            for (int colIndex = 0; colIndex < adviceCount; colIndex++)
            {
                if (_autoRun.RemainDrugDose[colIndex] > 0)
                {
                    if (_autoRun.RemainDrugDose[colIndex] < (double)_advicesForFlush.adviceAndDrugs[colIndex].adviceDrug[0].REALDOSE)
                    {
                        ShowRunState("结余模式:西林瓶内的剩余量不够新的医嘱使用，请点击换药后再继续配药！", LogLevel.Warning);
                        return false;
                    }
                }
            }
            return true;
        }

        private int TaskAutoRun()
        {
            bool ret=AutoRun();
            if(false==ret)
            {
                return 0;
            }
            return 1;
        }

        private void TaskAutoRunOver(Task<int> t)
        {
            BtnRunOver(t.Result);
        }

        private void BtnRunOver(int autoRunResult)
        {
            LogMessage("配药结束！");
            //自动配药结束后需要的处理
            //添加判断是否要屏蔽所有按钮
            if ((RunOkFlag == false) && (_nMotionCtrl.ExitType == 3))
            {
                //配药过程中，急停退出
                BtnReplaceIsEnabled = true;
                _needFlushBack = true;
                _CMD.CM_RunOver(0);
            }
            else
            {
                //配药正常结束
                EnableAllBtn();
                EnableConnectMode = false;
                EnableTPMode = false;
                _haveBottleInDevice = _autoRun.HaveBottleInDevice;
                _CMD.CM_RunOver(1);
            }
            _nMotionCtrl.IsAutoRun = 0;
            _IsRunning = 0;
            AutoRunBtnIsDown = false;
            _remainDrugDose = _autoRun.RemainDrugDose;
            _RecorderService.AddEndFlush(_adviceBars, _adviceBars.Count);

            _nMotionCtrl.WriteChannelOut(_nMotionCtrl.motionParam.nIOSet.oStartLed, 0);
            UpdateLEDAfterFlushOver();
            JudgeReplaceInjectorAfterRunOver();
            //配药结束，如果有新的医嘱，根据新的医嘱打开夹爪
            if (_advicesForFlush.adviceAndDrugs.Count > 0)
            {
                int closeIndex = _advicesForFlush.GetDJClosePosIndex();
                if (closeIndex != _DJCloseIndex)
                {
                    _DJCloseIndex = closeIndex;
                    TaskResetBottleJaw();
                }
            }

            _CMD.SetFocuse(1);
        }

        private bool AutoRun()
        {
            RunOkFlag = true;

            DateTime AutoRunStartTime = DateTime.Now;
            putEnd = DateTime.Now;
            TimeSpan ts1 = putEnd.Subtract(putStart);//计算放药时间
            int putTime = Convert.ToInt32(ts1.TotalSeconds);

            if (_workConfig.runningCloseLED == 0)
            {
                ContinueRefreshLED = false;//配药的时候不刷新LED灯
            }

            RunOkFlag = _autoRun.AutoRun();

            _autoRun.IsFinished = true;
            _nMotionCtrl.QuitAllMove = 0;
            putStart = DateTime.Now;
            DateTime AutoRunEndTime = DateTime.Now;
            TimeSpan ts = AutoRunEndTime.Subtract(AutoRunStartTime);
            int flushTime = Convert.ToInt32(ts.TotalSeconds);
            _CMD.EnableAll(1);
            return RunOkFlag;
        }

        //播报药品名称
        private void BroadcastDrugName()
        {
            List<string> drugNames = new List<string>();
            drugNames = GetDrugName();
            if (drugNames != null && drugNames.Count > 0)
            {
                if (1 == TPFlushMode)
                {
                    //统配模式配药
                    if (drugNames.Count > 0)
                    {
                        string drugName = drugNames[0];
                        string msg = "统配模式配药，药品名称是" + drugName;

                        SpeakAsync(msg);
                    }
                }
                else
                {
                    //散配模式
                    Speak("混配模式配药");
                    for (int i = 0; i < drugNames.Count; i++)
                    {
                        string drugName = drugNames[i];
                        string msg = (i + 1).ToString() + "号位，药品名称是" + drugName;
                        SpeakAsync(msg);
                    }
                }
            }
            else
            {
                ShowRunState("药品名称为空", LogLevel.Warning);
            }
        }

        #region 测试模式

        private int Task_TestMode()
        {
            bool continueRun = IO_Emg;
            while (continueRun)
            {
                RunOkFlag = _autoRun.AutoRun();
                if (false == RunOkFlag)
                {
                    continueRun = false;
                    break;
                }
                if (3 == _nMotionCtrl.ExitType)
                {
                    continueRun = false;
                    break;
                }
                continueRun = _nMotionCtrl.EmgState;
            }
            AutoRunBtnIsDown = false;
            return 1;
        }

        #endregion 测试模式

        #endregion 配药

        #region 换针

        public DelegateCommand ReplaceCommand
        {
            get { return new DelegateCommand(Replace).ObservesCanExecute(() => BtnReplaceIsEnabled); }
        }

        //换针
        private void Replace()
        {
            LogMessage("点击了换针按钮！");

            //添加判断，能不能换针，结余模式，设备上还有西林瓶则不能换针
            int needReplaceInjector = InjectorReachedUsageCountLimit();//是由达到使用寿命
            if (_surplusMode == 1)
            {
                //结余模式：
                if (_haveBottleInDevice == true)
                {
                    //设备上有西林瓶没有掉落

                    if (0 == needReplaceInjector)
                    {
                        //没有达到使用寿命，不能换针
                        ShowRunState("结余模式：设备上还有西林瓶，无法换针！", LogLevel.Warning);
                        return;
                    }
                }
            }

            if (0 == needReplaceInjector)
            {
                //没有达到使用寿命的换针，关闭LED灯刷新
                _scanedDrugs.Clear();
                MVDrugs.Clear();//清空需要编辑的药品
                ContinueRefreshLED = false;
                cLED.CloseAllLED();
                _CMD.CM_ReplaceInjectorStart(0);//开始换针
            }
            else
            {
                //达到使用寿命的换针
                _CMD.CM_ReplaceInjectorStart(1);//开始换针
            }
            if (0 == TPFlushMode)
            {
                //混配模式，需要选择需要更换的注射器
                ShowSelectedInjectorView();
            }
            //刷新显示加工信息

            _CMD.SetFocuse(1);
            ReplaceBtnIsDown = true;

            DisableAllBtn();

            TaskFactory factory = Task.Factory;
            Task<int> task = factory.StartNew<int>(TaskReplaceInjector);
            task.ContinueWith(TaskReplaceOver);
        }

        private void ThreadReplaceInjector()
        {
            ShowRunState("点击了换针按钮！", LogLevel.Information);
            bool ret = ReplaceInjector();
            EnableAllBtn();
            _autoRun.NeedleInBottle = false;
        }

        private int TaskReplaceInjector()
        {
            ShowRunState("点击了换针按钮！", LogLevel.Information);
            bool ret = ReplaceInjector();
            EnableAllBtn();
            _autoRun.NeedleInBottle = false;
            if (false == ret)
            {
                return 0;
            }
            return 1;
        }

        private bool ReplaceInjector()
        {
            try
            {
                if ((_nMotionCtrl == null) || (_nMotionCtrl.CardConnected == 0))
                {
                    return false;
                }
                //判断急停是否被按下，如果急停被按下，XY回零，否则，XY移动到零位
                bool emg = false;
                int ret1 = 0;
                ret1 = _nMotionCtrl.GetEmgState(ref emg);
                if (0 == ret1)
                {
                    return false;
                }
                else
                {
                    if (false == emg)
                    {
                        ShowRunState("急停按钮被按下，无法进行换针动作", LogLevel.Warning);
                        return false;
                    }
                    else
                    {
                        if (_nMotionCtrl.ExitType != 3)
                        {
                            //急停没有被按下，只要走到零位就可以另外
                            bool ret2 = MoveXYToZero();
                            if (false == ret2)
                            {
                                return false;
                            }
                        }
                        else
                        {
                            //急停被按下，XY需要回零,这个时候只能点击复位按钮
                            _nMotionCtrl.sAxisID = 1;
                            _nMotionCtrl.SingleAxisHome();
                            _nMotionCtrl.sAxisID = 0;
                            _nMotionCtrl.SingleAxisHome();
                            //添加对话框提示，是否要将注射器内的药液全部打回到溶媒
                            if (_needFlushBack == true)
                            {
                                _needFlushBack = false;
                                ButtonResult mr = ButtonResult.Yes;// MessageBox.Show("是否要将注射器内的液体打到溶媒袋里面去？", "操作提示", MessageBoxButton.YesNo);
                                Application.Current.Dispatcher.Invoke(
                                (Action)delegate ()
                                {
                                    _dialogService.ShowDialog("AlertDialog", new DialogParameters($"message={" 是否要将注射器内的液体打到溶媒袋里面去？"}"), r =>
                                    {
                                        mr = r.Result;
                                    });
                                });
                                if (mr == ButtonResult.Yes)
                                {
                                    _nMotionCtrl.QuitAllMove = 0;
                                    CMS_AnalyFile ms = new CMS_AnalyFile();
                                    COneRowStation oneRow = ms.InitializeOneRow(_workPoint.X_StationPos0);
                                    for (int i = 0; i < 8; i++)
                                    {
                                        oneRow.RowStations[i].UsedFlag = 1;
                                        oneRow.UsedDrug = sDrug;
                                    }
                                    int[] validCol = _autoRun.SolventRow.GetUsedFlag();
                                    _autoRun.Flush_SolventInAndPullInjector(_autoRun.SolventRow, validCol, 0);
                                    ShowRunState("注射器内的液体已经打回到溶媒袋，可以继续配药", LogLevel.Information);
                                    _nMotionCtrl.ExitType = 0;
                                    
                                }
                                else
                                {
                                    _nMotionCtrl.ExitType = 3;
                                    ShowRunState("请取出所有注射器后，在点击复位按钮，切记，切记......", LogLevel.Warning);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ShowRunState("执行出现异常：" + ex.Message, LogLevel.Warning);
            }
            return true;
        }

        private bool MoveXYToZero()
        {
            ret = _nMotionCtrl.AbsMove(1, 0);
            if (0 == ret)
            {
                return false;
            }
            ret = _nMotionCtrl.WaitForStop(1);
            if (0 == ret)
            {
                return false;
            }
            ret = _nMotionCtrl.AbsMove(0, 0);
            if (0 == ret)
            {
                return false;
            }
            ret = _nMotionCtrl.WaitForStop(0);
            if (0 == ret)
            {
                return false;
            }
            return true;
        }

        private void TaskReplaceOver(Task<int> tResult)
        {
            bool emg = false;
            ret = _nMotionCtrl.GetEmgState(ref emg);
            BtnRepalceInjectorOver(emg, tResult.Result);
        }

        private void BtnRepalceInjectorOver(bool emg, int taskResult)
        {
            if (1 == taskResult)
            {
                //判断急停按钮是否打开
                LogMessage("换针完成");
                if (false != emg)
                {
                    //只有急停打开才复位按钮使能
                    if ((RunOkFlag == false) && (_nMotionCtrl.ExitType == 3))
                    {
                        //XY回零，但所有Z轴没有回零，所以需要复位，换针动作正确完成后，才使能复位按钮
                        BtnResetIsEnabled = true;
                        ShowRunState("配药过程中急停按钮被按下，需要复位！", LogLevel.Warning);
                    }
                    else
                    {
                        //所有轴都已经有过回零动作了，所以不需要再复位了
                        EnableAllBtn();
                        //
                        if (DeviceConnectkMode > 0)
                        {
                            //扫码模式，换针后，可以更改，统配和混配模式
                            EnableTPMode = true;
                        }
                        ShowRunState("已经移动到换针位置，可以进行换针！", LogLevel.Information);
                    }
                }
                else
                {
                    DisableAllBtn();
                    BtnReplaceIsEnabled = true;
                }
                _CMD.SetFocuse(1);
                _remainDrugDose = _autoRun.RemainDrugDose;
                RefreshLabelAfterReplaceInjector();
                _CMD.CM_ReplaceInjectorOver(1);
            }
            ReplaceBtnIsDown = false;
        }

        #endregion 换针

        #region 放药

        //放药
        public DelegateCommand PutDrugCommand
        {
            get { return new DelegateCommand(PutDrug).ObservesCanExecute(() => BtnPutDrugIsEnabled); }
        }

        private void PutDrug()
        {
            LogMessage("点击了放药按钮");
            _CMD.SetFocuse(0);

            if (_nMotionCtrl.HomeOK == 1)
            {
                _CMD.CM_PutDrugStart(0);
                PutDrugBtnIsDown = true;

                _haveBottleInDevice = false;//设备上没有西林瓶
                DisableAllBtn();

                TaskFactory factory = Task.Factory;
                Task<int> task = factory.StartNew<int>(TaskPutDrug);
                task.ContinueWith(TaskPutDrugOver);
            }
            else
            {
                ShowRunState("没有回零，无法进行放药动作！", LogLevel.Warning);
            }
        }

        private int TaskPutDrug()
        {
            _autoRun.MoveToPutDrugPos();
            _DJCloseIndex = _workConfig.djClosePosIndex;
            _autoRun.cDJ.ResetJaw(_workConfig.djClosePosIndex);
            _autoRun.ResetRemainDrugDose();
            UpdateLED();
            _autoRun.NeedleInBottle = false;
            //同步朗读
            Application.Current.Dispatcher.Invoke(new Action(delegate { CRJSpeech.Speak("已经移动到放药位置，可以进行放药！"); }));
            DateTime putStart = DateTime.Now;

            return 1;
        }

        private void TaskPutDrugOver(Task<int> tResult)
        {
            BtnPutDrugOver(tResult.Result);
        }

        private void BtnPutDrugOver(int putDrugResult)
        {
            if (1 == putDrugResult)
            {
                LogMessage("移动到换药位置完成！");
                EnableAllBtn();
                _CMD.SetFocuse(1);
                PutDrugBtnIsDown = false;
                ShowRunState("已经移动到放药位置，可以进行放药！", LogLevel.Information);
                if ((_surplusMode == 1) && (DeviceConnectkMode == 0) && (_autoRun.BottleRemainIsZero() == 1))
                {
                    //儿科模式
                    _CMD.CM_PutDrugOver(1);
                }
            }
        }

        #endregion 放药

        #region 清空瓶贴

        //清空瓶贴
        public DelegateCommand ClearBottleLabelCommand
        {
            get { return new DelegateCommand(BtnClearBottleLabel).ObservesCanExecute(() => BtnClearIsEnabled); }
        }

        private void BtnClearBottleLabel()
        {
            LogMessage("点击了清空瓶贴按钮！");
            _CMD.SetFocuse(0);
            if ((DeviceConnectkMode > 0))
            {
                ContinueRefreshLED = false;
                cLED.CloseAllLED();
                _advicesForFlush.adviceAndDrugs.Clear();
                _CMD.ClearBottleLabel();
            }
            _CMD.SetFocuse(1);
        }

        #endregion 清空瓶贴

        #region 清洁

        //清洁
        public DelegateCommand BtnCleanCommand
        {
            get { return new DelegateCommand(BtnCleanClick).ObservesCanExecute(() => BtnCleanIsEnabled); }
        }

        private void BtnCleanClick()
        {
            LogMessage("点击了清洁按钮");
            _dialogService.ShowDialog("PUC_MS_Clean", null, null, GlobalDialogNames.CustomDialogWindow);
            _CMD.SetFocuse(1);
        }

        #endregion 清洁

        #region 药品编辑

        //选择药品combox
        public DelegateCommand DrugSCCommand
        {
            get { return new DelegateCommand(DrugSC).ObservesCanExecute(() => BtnDrugIsEnabled); }
        }

        private void DrugSC()
        {
            if (mvDrug != null)
            {
                //扫码模式
                DTO_adi_dic_drug drug = _scanedDrugs.Where(c => c.DRUG_CODE == mvDrug.DrugCode).FirstOrDefault();
                DialogParameters dialogParameters = new DialogParameters();
                dialogParameters.Add("DrugCode", drug);
                _dialogService.ShowDialog("PUC_DialogEditDrug", dialogParameters, AddDrugCallback, GlobalDialogNames.CustomDialogWindow);
            }
        }

        private void AddDrugCallback(IDialogResult dialogResult)
        {
            cbxSIndex_EditDrug = -1;
            if (dialogResult.Result == ButtonResult.Yes)
            {
                LogMessage("保存成功");
                _CMD.SetFocuse(1);
            }
            else
            {
                LogMessage("退出！");
            }
        }

        #endregion 药品编辑

        #endregion 界面按钮指令

        #region 选择注射器更换

        private void ShowSelectedInjectorView()
        {
            string DialogName = "View_SelectInjector";
            DialogParameters dialogParameters = new DialogParameters();
            string str = "1-0-1-1-0-0";
            if (_deviceConfig.StationColNum == 4)
            {
                str = "1-1-1-1-0-0";
            }
            else
            {
                str = "1-1-1-1-1-1";
            }
            dialogParameters.Add("SelectedInjector", str);
            _dialogService.ShowDialog(MSDM_DialogNames.SelectInjector, dialogParameters,
                SelectedInjectorCallback, GlobalDialogNames.CustomDialogWindow);
        }

        private void SelectedInjectorCallback(IDialogResult dialogResult)
        {
            if (dialogResult.Result == ButtonResult.OK)
            {
                Message = dialogResult.Parameters.GetValue<string>("SelectedInjector");
                string[] arr = Message.Split("-");
                for (int i = 0; i < arr.Length; i++)
                {
                    if (arr[i] == "0")
                    {
                        _array_InjectorHadUsed[i] = true;
                    }
                    else
                    {
                        //选择了换针
                        _array_InjectorHadUsed[i] = false;//注射器使用标志位
                        _array_InjectorHadUsedCount[i] = 0;//注射器使用次数

                        #region renjie

                        //scanBar.currentUsedDrugs[i] = new DTO_adi_dic_drug();

                        #endregion renjie
                    }
                }
            }
        }

        private string GetCanNotUsedInjector()
        {
            string str = "站号：";
            for (int i = 0; i < ValidStation; i++)
            {
                if (_array_InjectorHadUsedCount[i] >= _deviceConfig.InjectorAllowUsedCount)
                {
                    str = str + i.ToString() + "-";
                }
            }
            str = str + "注射器达到使用寿命";
            return str;
        }

        //判断是否有注射器达到使用寿命
        private bool HaveInjectorAxceedWorkingLife()
        {
            for (int i = 0; i < ValidStation; i++)
            {
                if (_array_InjectorHadUsedCount[i] >= _deviceConfig.InjectorAllowUsedCount)
                {
                    return true;
                }
            }
            return false;
        }

        //所有的注射器都没有使用过
        private bool AllInjectorHadNotUsed()
        {
            for (int i = 0; i < ValidStation; i++)
            {
                if (true == _array_InjectorHadUsed[i])
                {
                    return false;
                }
            }
            return true;
        }

        private void InitializeInjetor()
        {
            for (int i = 0; i < 6; i++)
            {
                _array_InjectorHadUsed[i] = false;
                _array_InjectorHadUsedCount[i] = 0;
            }
        }

        #endregion 选择注射器更换

        #region combox

        //更改联机模式
        public DelegateCommand ConnetModeSelectedChangedCommand
        {
            get { return new DelegateCommand(ConnetModeChange).ObservesCanExecute(() => EnableConnectMode); }
        }

        private void ConnetModeChange()
        {
            _topParam.DeviceConnectkMode = DeviceConnectkMode;
            if (0 == DeviceConnectkMode)
            {
                //单机模式
                EnableTPMode = false;
                TPFlushMode = 1;//单机模式只有统配模式
                BtnClearIsEnabled = false;
                NavigateToTop();
                _scanBarMode = false;
                _CMD.ClearBottleLabel();
            }
            else
            {
                //扫码模式
                EnableTPMode = true;
                BtnClearIsEnabled = true;
                NavigateToTop();
                _CMD.ClearBottleLabel();
            }
        }

        //更改统配模式
        public DelegateCommand TPModeSelectedChangedCommand
        {
            get { return new DelegateCommand(TPModeChange).ObservesCanExecute(() => EnableTPMode); }
        }

        private void TPModeChange()
        {
            _topParam.TPFlushMode = TPFlushMode;
            if (TPFlushMode == 0)
            {
                ShowRunState("混配模式：必须扫一个医嘱后，将该医嘱对应的溶媒水袋和西林瓶药放入设备后，才可以扫描下一个医嘱！切结！");
            }
            else
            {
                ShowRunState("统配模式");
            }
            _CMD.CM_TPFlushMode(TPFlushMode);
            _CMD.ClearBottleLabel();
        }

        #endregion combox

        #region private function

        private void ShowRunState(string str, LogLevel level = LogLevel.Warning)
        {
            if (str.Length < 1)
            {
                return;
            }

            if (str != RunState)
            {
                RunState = str;
                LogMessage(str, level);
            }
        }

        private void SpeakAsync(string msg)
        {
            try
            {
                if (_workConfig.EnableSpeek == 1)
                {
                    Task t = new Task(() =>
                    {
                        Application.Current.Dispatcher.Invoke(new Action(delegate { CRJSpeech.SpeakAsync(msg); }));
                    });
                    t.Start();
                }
            }
            catch (Exception e)
            {
            }
        }

        private void Speak(string msg)
        {
            try
            {
                if (_workConfig.EnableSpeek == 1)
                {
                    Task t = new Task(() =>
                    {
                        Application.Current.Dispatcher.Invoke(new Action(delegate { CRJSpeech.Speak(msg); }));
                    });
                    t.Start();
                }
            }
            catch (Exception e)
            {
            }
        }

        #endregion private function
    }
}